import React, { memo, useRef } from 'react';
import ReactEcharts from 'echarts-for-react';

import { PLACE_HOLDER } from '@/pages/SalaryManage/components/EmptyPlaceHolder';
import { numberFormat } from '@/utils/formatterUtil';

const sunburstColor = ['#ffb133', '#ff7a7a', '#69d1b1', '#9db7ff', '#ffd38c', '#a1e2ce', '#ffabab', '#ffeccc', '#c8d6ff']

const sunburstDataInheritFn = (data, color, opacity) => data && data.map(item => ({
        ...item,
        value: parseFloat(item.value),
        text: item.value,
        itemStyle: {
            color,
            opacity: opacity / 10
        },
        children: sunburstDataInheritFn(item.children, color, opacity !== 2 ? (opacity - 1) : opacity)
    }))

// 旭日图颜色，下钻到子节点不是一个节点的层级，然后部门颜色按照UI给的遍历循环，对应的子节点颜色继承父元素，透明度-0.1,
const sunburstDataParamFn = data => {
    if (data.length === 1) {
        return data.map(item => ({
            ...item,
            value: parseFloat(item.value),
            text: item.value,
            children: sunburstDataParamFn(item.children)
        }))
    }

    return data.map((item, index) => ({
        ...item,
        value: parseFloat(item.value),
        text: item.value,
        itemStyle: {
            color: sunburstColor[(index + 1) % sunburstColor.length]
        },
        children: sunburstDataInheritFn(item.children, sunburstColor[(index + 1) % sunburstColor.length], 9)
    }))
}

// 不同图表tip不同展示
const typeFormatterMap = {
    // 组织薪资（加项汇总）
    addSummaryOrg: (...arg) => {
        const { data: formatterData } = arg[0]
        const { name, count, text } = formatterData
        return !name ? null : `<span style="color: rgba(0,0,0,0.45)">${name}(${numberFormat(count, '')}人次)</span><br />合计金额：${numberFormat(text, '')}`;
    },
    // 部门人均薪资（加项汇总）
    addSummaryPersonal: (...arg) => {
        const { data: formatterData } = arg[0][0]
        const { itemAmt, itemCount, itemName } = formatterData
        return `<span style="color: rgba(0,0,0,0.45)">${itemName}(${numberFormat(itemCount, '')}人次)</span><br />人均：${numberFormat(itemAmt, '')}`;
    },
    // 岗位薪资（加项汇总）
    addSummaryPost: (...arg) => {
        const { data: formatterData } = arg[0][0]
        const { itemAmt, itemCount, levelName, itemName } = formatterData
        return `<span style="color: rgba(0,0,0,0.45)">${levelName}-${itemName}(${numberFormat(itemCount, '')}人次)</span><br />合计金额：${numberFormat(itemAmt, '')}`;
    },
    // 薪资结构对比（加项汇总）
    addSummaryStructCompare: (...arg) => {
        const { data: formatterData } = arg[0]
        const { itemAmt, itemRate, itemName, referenceValueMin = '' } = formatterData
        return `<span style="color: rgba(0,0,0,0.45)">${itemName}</span><br />合计金额：${numberFormat(itemAmt, '')}<br />占薪资比重：${itemRate === '' ? PLACE_HOLDER : (`${itemRate}%`)}<br />参考值：${numberFormat(referenceValueMin, '')}${String(referenceValueMin).length > 0 ? '%' : PLACE_HOLDER}`;
    },
    // 组织对比（加项汇总）
    addSummaryOrgCompare: (...arg) => {
        const { data: formatterData } = arg[0]
        const { itemAmt, itemRate, itemName, referenceValueMin = '' } = formatterData
        return `<span style="color: rgba(0,0,0,0.45)">${itemName}</span><br />合计金额：${numberFormat(itemAmt, '')}<br />占总薪资比重：${itemRate === '' ? PLACE_HOLDER : (`${itemRate}%`)}<br />参考值：${numberFormat(referenceValueMin, '')}${String(referenceValueMin).length > 0 ? '%' : PLACE_HOLDER}`;
    },
    // 组织薪资（减项汇总）
    subSummaryOrg: (...arg) => {
        const { data: formatterData } = arg[0]
        const { name, count, text, other = [] } = formatterData
        const formatterItems = () => {
            let str = ''
            other.forEach(({ name: itemName, amt }) => {
                str += `<span>${itemName}：${numberFormat(amt, '')}</span><br />`
            })
            return str
        }

        return !name ? null : `<span style="color: rgba(0,0,0,0.45)">${name}(${numberFormat(count, '')}人次)</span><br />合计金额：${numberFormat(text, '')}<br /> ${formatterItems()}`;
    },
    // 单位险金（减项汇总）
    subSummarySocialTaxCompany: (...arg) => {
        const { data: formatterData } = arg[0][0]
        const { itemAmt, itemName, other } = formatterData
        const formatterItems = () => {
            let str = ''
            other.forEach(({ name, amt }) => {
                str += `<span>${name}：${numberFormat(amt, '')}</span><br />`
            })
            return str
        }
        return `<span style="color: rgba(0,0,0,0.45)">${itemName}</span><br />合计金额：${numberFormat(itemAmt, '')}<br />${formatterItems()}`;
    },
    // 组织薪资（实发薪资）
    actualSalaryOrg: (...arg) => {
        const { data: formatterData } = arg[0]
        const { name, count, text } = formatterData

        return !name ? null : `<span style="color: rgba(0,0,0,0.45)">${name}(${numberFormat(count, '')}人次)</span><br />合计金额：${numberFormat(text, '')}`;
    },
    // 部门人均（实发薪资）
    actualSalaryPersonal: (...arg) => {
        const { data: formatterData } = arg[0][0]
        const { itemAmt, itemCount, itemName } = formatterData
        return `<span style="color: rgba(0,0,0,0.45)">${itemName}(${numberFormat(itemCount, '')}人次)</span><br />人均：${numberFormat(itemAmt, '')}`;
    },
    // 岗位薪资（实发薪资）
    actualSalaryPost: (...arg) => {
        const { data: formatterData } = arg[0][0]
        const { itemCount, itemAmt, levelName, itemName } = formatterData
        return `<span style="color: rgba(0,0,0,0.45)">${levelName}-${itemName}(${numberFormat(itemCount, '')}人次)</span><br />合计金额：${numberFormat(itemAmt, '')}`;
    },
    // 增长趋势（薪资细项）
    salaryDetailGrowthTrend: (...arg) => {
        const { data: formatterData } = arg[0][0]
        const { itemAmt, itemId, itemName } = formatterData
        return `<span style="color: rgba(0,0,0,0.45)">${itemName}</span><br />${itemId}月：${numberFormat(itemAmt, '')}`;
    },
    // 结构对比（薪资细项）
    salaryDetailStructCompare: (...arg) => {
        const formatterArr = arg[0]
        const formatterItems = () => {
            let str = ''
            formatterArr.forEach(({ seriesName, value }) => {
                str += `<span>${seriesName}：${numberFormat(value, '')}</span><br />`
            })
            return str
        }
        return `<span style="color: rgba(0,0,0,0.45)">${formatterArr[0]?.name}</span><br />${formatterItems()}`
    }
}

// 根据不同图表获取不同配置
const seriesTypeMap = (chartType, itemType, data) => {
    switch (chartType) {
        case 'line':
            return ({
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    backgroundColor: '#fff',
                    textStyle: {
                        color: 'rgba(0, 0, 0, 0.65)'
                    },
                    axisPointer: {
                        type: 'none'
                    },
                    formatter: typeFormatterMap[itemType],
                    extraCssText: 'box-shadow: 0 4px 16px 0 rgba(0,0,0,0.12);'
                },
                xAxis: {
                    type: 'category',
                    boundaryGap: false,
                    axisLine: {
                        lineStyle: {
                            color: '#ededed'
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: 'rgba(0, 0, 0, 0.45)'
                        },
                        margin: 20
                    },
                    axisTick: {
                        show: true,
                        length: 12,
                        lineStyle: {
                            color: '#ededed'
                        }
                    },
                    data: data.map(item => `${item.itemId}月`)
                },
                grid: {
                    left: '1%',
                    right: '2.5%',
                    bottom: '3%',
                    containLabel: true
                },
                color: ['#5590F6'],
                yAxis: {
                    type: 'value',
                    axisLine: {
                        show: false,
                        lineStyle: {
                            color: 'rgba(0, 0, 0, 0.45)'
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: '#ededed'
                        }
                    }
                },
                series: [{
                    symbol: 'circle',
                    symbolSize: 6,
                    data: data.map(item => ({
                        ...item,
                        value: item.itemAmt
                    })),
                    type: 'line'
                }]
            })
        case 'bar':
            return ({
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    backgroundColor: '#fff',
                    textStyle: {
                        color: 'rgba(0, 0, 0, 0.65)'
                    },
                    transitionDuration: 0,
                    axisPointer: {
                        type: 'shadow',
                        shadowStyle: {
                            color: '#000',
                            opacity: 0.03
                        }
                    },
                    formatter: typeFormatterMap[itemType],
                    extraCssText: 'box-shadow: 0 4px 16px 0 rgba(0,0,0,0.12);'
                },
                color: ['#85A5FF'],
                xAxis: {
                    type: 'category',
                    axisLine: {
                        lineStyle: {
                            color: '#ededed'
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: 'rgba(0, 0, 0, 0.45)'
                        },
                        margin: 20
                    },
                    axisTick: {
                        show: true,
                        length: 12,
                        lineStyle: {
                            color: '#ededed'
                        }
                    },
                    data: data.map(item => item.itemName)
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        show: false,
                        lineStyle: {
                            color: 'rgba(0, 0, 0, 0.45)'
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: '#ededed'
                        }
                    }
                },
                grid: {
                    left: '1%',
                    right: '2.5%',
                    bottom: '3%',
                    top: 10,
                    containLabel: true
                },
                series: {
                    type: 'bar',
                    barMaxWidth: 50,
                    barMinHeight: 1,
                    barGap: '20%',
                    legendHoverLink: true,
                    showBackground: true,
                    label: {
                        verticalAlign: 'middle'
                    },
                    itemStyle: {
                        normal: {
                            barBorderRadius: [2, 2, 0, 0]
                        }
                    },
                    barCategoryGap: '30%',
                    data: data.map(item => ({
                        ...item,
                        value: item.itemAmt
                    }))
                }
            })
        case 'stackBar':
            return ({
                tooltip: {
                    show: true,
                    trigger: 'axis',
                    backgroundColor: '#fff',
                    textStyle: {
                        color: 'rgba(0, 0, 0, 0.65)'
                    },
                    axisPointer: {
                        type: 'shadow',
                        shadowStyle: {
                            color: '#000',
                            opacity: 0.03
                        }
                    },
                    formatter: typeFormatterMap[itemType],
                    extraCssText: 'box-shadow: 0 4px 16px 0 rgba(0,0,0,0.12);'
                },
                legend: {
                    bottom: 5,
                    itemGap: 30,
                    itemWidth: 12,
                    itemHeight: 12,
                    borderRadius: 4,
                    data: data.map(item => item.salaryItemName)
                },
                grid: {
                    top: '2%',
                    left: '1%',
                    right: '2.5%',
                    bottom: '10%',
                    containLabel: true
                },
                color: sunburstColor,
                xAxis: {
                    type: 'category',
                    axisLine: {
                        lineStyle: {
                            color: '#ededed'
                        }
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: 'rgba(0, 0, 0, 0.45)'
                        },
                        margin: 20
                    },
                    axisTick: {
                        show: true,
                        length: 12,
                        lineStyle: {
                            color: '#ededed'
                        }
                    },
                    data: data[0]?.yearMonthList || []
                },
                yAxis: {
                    type: 'value',
                    axisLine: {
                        show: false,
                        lineStyle: {
                            color: 'rgba(0, 0, 0, 0.45)'
                        }
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: '#ededed'
                        }
                    }
                },
                series: data.map(item => ({
                    name: item.salaryItemName,
                    type: 'bar',
                    barMaxWidth: 50,
                    stack: '条形堆叠',
                    data: item.salaryItemAmtList
                }))
            })
        case 'sunburst':
            return ({
                tooltip: {
                    show: true,
                    backgroundColor: '#fff',
                    textStyle: {
                        color: 'rgba(0, 0, 0, 0.65)'
                    },
                    extraCssText: 'box-shadow: 0 4px 16px 0 rgba(0,0,0,0.12);',
                    formatter: typeFormatterMap[itemType]
                },
                color: sunburstColor,
                series: {
                    type: 'sunburst',
                    data: sunburstDataParamFn(data),
                    radius: [0, '100%'],
                    emphasis: {
                        focus: 'descendant'
                    },
                    label: {
                        rotate: 0,
                        align: 'center',
                        minAngle: 20,
                        color: 'rgba(0,0,0,0.65)'
                    }
                }
            })
        case 'bullet':
            return ({
                yAxis: [{
                    type: 'category',
                    data: data.map(item => item.itemName),
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    }
                }, {
                    type: 'category',
                    data: [''],
                    axisLine: {
                        show: false
                    },
                    axisTick: {
                        show: false
                    }
                }],
                xAxis: {
                    type: 'value',
                    position: 'top',
                    axisLine: {
                        show: false
                    },
                    axisLabel: {
                        show: true,
                        textStyle: {
                            color: 'rgba(0, 0, 0, 0.45)'
                        },
                        formatter: '{value}%',
                        margin: 20
                    },
                    axisTick: {
                        show: false
                    },
                    splitLine: {
                        lineStyle: {
                            type: 'dashed',
                            color: '#ededed'
                        }
                    }
                },
                grid: {
                    top: 10,
                    left: '1%',
                    right: '2.5%',
                    bottom: '10%',
                    containLabel: true
                },
                tooltip: {
                    backgroundColor: '#fff',
                    textStyle: {
                        color: 'rgba(0, 0, 0, 0.65)'
                    },
                    formatter: typeFormatterMap[itemType],
                    extraCssText: 'box-shadow: 0 4px 16px 0 rgba(0,0,0,0.12);'
                },
                legend: {
                    data: ['实际值', '参考值'],
                    selectedMode: false,
                    bottom: 5,
                    itemGap: 20,
                    itemWidth: 12,
                    itemHeight: 12,
                    borderRadius: 4
                },
                series: [{
                    name: '实际值',
                    data: data.map(item => ({
                        ...item,
                        value: item.itemRate
                    })),
                    type: 'bar',
                    barWidth: 15,
                    color: '#85A5FF',
                    z: 3

                }, {
                    name: '参考值',
                    type: 'scatter',
                    symbol: 'roundRect',
                    symbolSize: [3, 24],
                    data: data.map(item => ({
                        ...item,
                        value: item.referenceValueMin
                    })),
                    color: '#FFC069',
                    z: 4
                }]
            })
        default:
            return {

            }
    }
}

const ItemChart = ({ chartType, itemType, optionData }) => {
    const chartRef = useRef(null);
    const getOption = () => seriesTypeMap(chartType, itemType, optionData)
    return <ReactEcharts ref={chartRef} option={getOption()} style={{ height: 360 }} />;
};

export default memo(ItemChart);
